package com.cj.kvstore

import android.util.Log
import java.io.*

@Suppress("UNCHECKED_CAST")
class ObjectSerializer {
    companion object{
        fun <T : Serializable> fromByteArray(byteArray: ByteArray): T? {
            var byteArrayInputStream:ByteArrayInputStream? = null
            var objectInput:ObjectInputStream? = null
            try{
                byteArrayInputStream = ByteArrayInputStream(byteArray)
                objectInput = ObjectInputStream(byteArrayInputStream)
                return objectInput.readObject() as? T?
            }catch (e:Exception){
                Log.e("KVStore", "Serializable -> read object fail:$e")
                e.printStackTrace()
            }finally {
                objectInput?.close()
                byteArrayInputStream?.close()
            }
            return null
        }

        fun toByteArray(value: Serializable): ByteArray? {
            var byteArrayOutputStream:ByteArrayOutputStream? = null
            var objectOutputStream:ObjectOutputStream? = null
            try {
                byteArrayOutputStream = ByteArrayOutputStream()
                objectOutputStream = ObjectOutputStream(byteArrayOutputStream)
                objectOutputStream.writeObject(value)
                objectOutputStream.flush()
                return byteArrayOutputStream.toByteArray()
            }catch (e:Exception){
                Log.e("KVStore", "Serializable -> write object fail:$e")
                e.printStackTrace()
            }finally {
                byteArrayOutputStream?.close()
                objectOutputStream?.close()
            }
            return null
        }
    }
}